﻿'use strict';

// todoPage controller
app.controller('processingSheet', ['$stateParams','$state','$filter','$window','$http','$scope','$modal','toaster','$log', function($stateParams,$state,$filter,$window,$http,$scope,$modal,toaster,$log) {
    function inIt(){
        if($stateParams.docId===null){
            getList();
        }else if($stateParams.docId==="new"){
            $scope.warehouseJump();
        }else{
            toaster.getInfo('/a_yongan/single/processprocess/'+$stateParams.docId,null).then(function(data){
                if(data && data.data && data.data.data){
                    makeData([data.data.data],true);
                }
            });

        }
    }
    $scope.canEdit = false;
    $scope.goods=[];//定义数组
    //添加的方法
    function addRows(name,j){
        var id = new Date().getTime()+j;
        var go = {
            "processDetailsId":id,
            "processDetailsName":name,
            "processDetailsCzr":"",
            "processDetailsCzrId":"",
            "processDetailsGxnr":"",
            "processDetailsGxsc":"",
            "processDetailsBzgs":"",
            "processDetailsWcsl":"",
            "processDetailsWwcsl":"",
            "processDetailsJyy":"",
            "processDetailsJyyId":""
        }
        $scope.goods.push(go);
    };
    $scope.changeDetails={
        processDetailsGxnr:function(index){
            $scope.goods[index].processDetailsGxnr = $("#"+$scope.goods[index].processDetailsId+"processDetailsGxnr").val();
        },
        processDetailsBzgs:function(index){
            $scope.goods[index].processDetailsBzgs = $("#"+$scope.goods[index].processDetailsId+"processDetailsBzgs").val();
        },
        processDetailsGxsc:function(index){
            $scope.goods[index].processDetailsGxsc = $("#"+$scope.goods[index].processDetailsId+"processDetailsGxsc").val();
        },
        processDetailsWcsl:function(index){
            $scope.goods[index].processDetailsWcsl = $("#"+$scope.goods[index].processDetailsId+"processDetailsWcsl").val();
        },
        processDetailsWwcsl:function(index){
            $scope.goods[index].processDetailsWwcsl = $("#"+$scope.goods[index].processDetailsId+"processDetailsWwcsl").val();
        }
    }
    $scope.title = {
        title:'工艺加工单列表',
        addTitle:'工艺加工单信息'
    };

    $scope.showJGDetails = function(){
        //var val = $('#processProcessType').val();
        var val = $scope.lists[$('#processProcessType').val()];
        if(val==='阀体类'){
            $scope.goods=[];
            addRows("打压",1);
            addRows("车床加工",2);
            addRows("铣床加工",3);
            addRows("钻床加工",4);
            addRows("喷塑",5);
        }else if(val==='阀座类'){
            $scope.goods=[];
            addRows("车床加工",1);
            addRows("委托外协",2);
            addRows("钻床加工",3);
        }else if(val==='阀杆类'){
            $scope.goods=[];
            addRows("打压",1);
            addRows("车床加工",2);
            addRows("钻床加工",3);
        }else if(val==='阀盖类'){
            $scope.goods=[];
            addRows("车床加工",1);
            addRows("钻床加工",2);
        }
    }
    $scope.toaster = {
        type: 'warning',
        title: '提示：',
        text: '内容不能为空！'
    };
    $scope.heji = {"zgs":0,"wchj":0,"wwhj":0};
    function makeData(data,single){
        $scope.heji = {"zgs":0,"wchj":0,"wwhj":0};
        data.forEach(function (item) {
            item.createTime = $filter("date")(item.createTime, "yyyy/MM/dd");
            item.processProcessKgrq = $filter("date")(item.processProcessKgrq, "yyyy/MM/dd");
            item.processProcessWgrq = $filter("date")(item.processProcessWgrq, "yyyy/MM/dd");
            item.zgs = 0;
            item.wchj = 0;
            item.wwhj = 0;
            item.details.forEach(function(detail){
                item.zgs = item.zgs + (parseFloat(detail.processDetailsGxsc)||0);
                item.wchj = item.wchj + (parseFloat(detail.processDetailsWcsl)||0);
                item.wwhj = item.wwhj + (parseFloat(detail.processDetailsWwcsl)||0);
            });
            $scope.heji.zgs = $scope.heji.zgs + parseFloat(item.zgs);
            $scope.heji.wchj = $scope.heji.wchj + parseFloat(item.wchj);
            $scope.heji.wwhj = $scope.heji.wwhj + parseFloat(item.wwhj);
            if(item.state.indexOf("办结")>=0){
                item.status1 = 'label bg-danger';
            }else{
                item.status1 = 'label bg-info';
            }
        })
        if(single){
            $scope.showInfo(data[0]);
        }else{
            $scope.saveDate = data;
        }
    }
    function getList(){
        toaster.getInfo('/a_yongan/list/processprocess',null).then(function(data){
            if(data && data.data && data.data.data){
                makeData(data.data.data);
            }
        });
    }
    $scope.pop = function(){
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    };
    function showMessage(type,title,text){
        $scope.toaster.type = type;
        $scope.toaster.text = text;
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    }
    function checkItems(){
        var items = ['processProcessType','processProcessKgrq','processProcessWgrq'];
        var itemsValue = ['生产类型','开工日期','完工日期'];
        for(var i=0;i<items.length;i++){
            if($('#'+items[i]+'').val()===''){
                $('#'+items[i]+'').focus();
                showMessage('warning','',itemsValue[i]+"不能为空！");
                return false;
            }
        }
        if(!($('#processProcessType option:selected') && $('#processProcessType option:selected').text()!=="")){
            showMessage('warning','',"生产类型不能为空！");
            return false;
        }
        return true;
    }
    $scope.message = '';
    $scope.saveInfo = function (size,msg) {
        var type='';
        if(msg==='th'){
            type = '退回';
        }else if(msg==='bc'){
            type = '保存';
        }else if(msg==='tj'){
            type ='提交';
        }else{
            return;
        }
        $scope.message = '是否确定'+type+'？';
        if(!checkItems()){
            return;
        }
        if(!forcheck($("#processProcessSl").val())){
            return;
        }
        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            size: size,
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            var info = addDo(msg);
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.isshow=true;
    $scope.warehouseAdd = false;
    $scope.warehouseList = true;
    $scope.warehouseJump = function(ts) {
        if(ts!=='back'){
            $scope.canEdit = true;
            $scope.row = {};
            $scope.showFiles = [];
            $scope.goods=[];
            $scope.row = {
                'createTime':$filter("date")(new Date(), "yyyy/MM/dd"),
                'zdr':$scope.app.userName,
                'upDateUserId':"new",
                'processProcessJgdh':'JGD'+$filter("date")(new Date(), "yyyyMMddHHmmss")
            };
        }else{
            $scope.canEdit = false;
            getList();
        }
        $scope.warehouseAdd = !($scope.warehouseAdd);
        $scope.warehouseList = !($scope.warehouseList);
    };
    $scope.row = {};
    $scope.columns = [
        {
            title:'创建时间',
            show:true
        },
        {
            title:'单据编号',
            show:true
        },
        {
            title:'计划单号',
            show:true
        },
        {
            title:'开工日期',
            show:true
        },
        {
            title:'货品名称',
            show:true
        },
        {
            title:'文件状态',
            show:true
        },
        {
            title:'总耗工时(小时)',
            show:true
        },
        {
            title:'检验员',
            show:true
        },
        {
            title:'操作人',
            show:true
        },
        {
            title:'完成合计',
            show:true
        },
        {
            title:'未完合计',
            show:true
        },
        {
            title:'耗时(小时)',
            show:true
        },
        {
            title:'操作',
            show:true
        }
    ];
    $scope.showSelectGoods = function(name,id){
        var modalInstance = $modal.open({
            templateUrl: 'selectGoods.html',
            controller: 'selectGoodsCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            if(name&&id){
                $("#"+name).val(selectedItem.name);
                $("#"+id).val(selectedItem.id);
            }else{
                $("#processProcessHpmc").val(selectedItem.name);
                $("#processProcessHpmcId").val(selectedItem.id);
                $("#processProcessGgxh").val(selectedItem.hpxh);
            }
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    function forcheck(ss) {
        var type = "^[0-9]*[1-9][0-9]*$";
        var re = new RegExp(type);
        if (ss.match(re) == null) {
            showMessage('warning','','"数量"请输入大于零的整数!');
            $scope.row.processProcessSl = '';
            return false;
        }
        return true;
    }
    $scope.showSelectUser = function(index,id,name,nameid){
        var modalInstance = $modal.open({
            templateUrl: 'selectUser.html',
            controller: 'selectUserCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            if(id=='processDetailsJyy'){
                $scope.goods[index].processDetailsJyy = selectedItem.name;
                $scope.goods[index].processDetailsJyyId = selectedItem.id;
            }else if(id=='processDetailsCzr'){
                $scope.goods[index].processDetailsCzr = selectedItem.name;
                $scope.goods[index].processDetailsCzrId = selectedItem.id;
            }else{
                $('#'+name+'').val(selectedItem.name);
                $('#'+nameid+'').val(selectedItem.id);
            }
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.saveDate=[];
    $scope.showInfo = function(row){
        $scope.row = row;
        $scope.goods = row.details;
        $scope.showFlowDetailsShow = false;
        $scope.showFlowDetailsData = [];
        //判断有没有编辑的权限
        if($scope.row.processProcessId && $scope.row.processProcessId!==""){
            toaster.getInfo('/a_yongan/single/editpower/'+$scope.row.processProcessId,null).then(function(data){
                if(data && data.data){
                    $scope.canEdit = data.data.success;
                }
            });
        }
        $scope.warehouseAdd = !($scope.warehouseAdd);
        $scope.warehouseList = !($scope.warehouseList);
        $scope.mylabel = $scope.row.processProcessType;
        getAllFile();
    };
    $scope.lists = ['','阀体类','阀盖类','阀杆类','阀座类'];
    $scope.listsJg = ['',"打压","车床加工","铣床加工","钻床加工","喷塑","委托外协"];
    $scope.mylabelJg = "";
    $scope.mylabel = $scope.lists[0];
    $scope.showProductionPlan = function(){
        var modalInstance = $modal.open({
            templateUrl: 'selectProductionPlan.html',
            controller: 'selectProductionPlanCtrl',
            size: 'lg',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            $scope.row.processProcessScjh = selectedItem.productionPlanDjbh;
            $scope.row.processProcessHpmc = selectedItem.productionPlanHpmc;
            $scope.row.processProcessHpmcId = selectedItem.productionPlanHpmcId;
            $scope.row.processProcessGgxh = selectedItem.productionPlanGgxh;
            $scope.row.processProcessSl = selectedItem.productionPlanSl;
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    function addDo(type){
        var notesdata = {};
        if($scope.canEdit){
            if(!$scope.row.processProcessId){
                notesdata = {
                    "processProcessId":"",
                    //"qy":$("#qy").prop("checked"),
                    "zdr":$scope.app.userName,
                    "zdrId":$scope.app.userId,
                    "processProcessJgdh":$("#processProcessJgdh").val(),
                    "processProcessScjh":$("#processProcessScjh").val(),
                    "processProcessKgrq":new Date($("#processProcessKgrq").val()).getTime(),
                    "processProcessWgrq":new Date($("#processProcessWgrq").val()).getTime(),
                    "processProcessHpmc":$("#processProcessHpmc").val(),
                    "processProcessHpmcId":$("#processProcessHpmcId").val(),
                    "processProcessGgxh":$("#processProcessGgxh").val(),
                    "processProcessSl":$("#processProcessSl").val(),
                    "processProcessType":$scope.lists[$("#processProcessType").val()],
                    "processProcessBz":$("#processProcessBz").val(),
                    "details":$scope.goods
                }
            }else{
                notesdata = {
                    "processProcessId":$scope.row.processProcessId,
                    //"qy":$("#qy").prop("checked"),
                    "processProcessJgdh":$("#processProcessJgdh").val(),
                    "processProcessScjh":$("#processProcessScjh").val(),
                    "processProcessKgrq":new Date($("#processProcessKgrq").val()).getTime(),
                    "processProcessWgrq":new Date($("#processProcessWgrq").val()).getTime(),
                    "processProcessHpmc":$("#processProcessHpmc").val(),
                    "processProcessHpmcId":$("#processProcessHpmcId").val(),
                    "processProcessGgxh":$("#processProcessGgxh").val(),
                    "processProcessSl":$("#processProcessSl").val(),
                    "processProcessType":$scope.lists[$("#processProcessType").val()],
                    "processProcessBz":$("#processProcessBz").val(),
                    "details":$scope.goods
                }
            }
        }else{
            $scope.row.processProcessKgrq = new Date($scope.row.processProcessKgrq).getTime();
            $scope.row.processProcessWgrq = new Date($scope.row.processProcessWgrq).getTime();
            $scope.row.createTime = new Date($scope.row.createTime).getTime();
            notesdata = $scope.row;
        }
        var info="";
        toaster.postInfo('/a_yongan/add/processprocess',notesdata).then(function(data){
            if(data && data.data && data.data.success && data.data.data){
                if(type!=='bc'){
                    var params = {
                        "id":data.data.data.personalWorkDocId,
                        "type":1,
                        "flow":"processprocess",
                        "data":data.data.data
                    };
                    if(type==="th"){
                        params.type = -1;
                    }
                    toaster.postInfo('/a_yongan/workflow/processprocess',params).then(function(data){
                        if(data && data.data && data.data.success){
                            showMessage('seccess','','操作成功！');
                            $scope.warehouseAdd = !($scope.warehouseAdd);
                            $scope.warehouseList = !($scope.warehouseList);
                            getList();
                            return info;
                        }else{
                            showMessage('warning','','操作失败！');
                            info = "请求错误！";
                        }
                    });
                }else{
                    showMessage('seccess','','保存成功！');
                    $scope.warehouseAdd = !($scope.warehouseAdd);
                    $scope.warehouseList = !($scope.warehouseList);
                    getList();
                    return info;
                }
                //return info;
            }else{
                showMessage('warning','','保存失败！');
                info = "请求错误！";
            }
        });
        return info;
    };

    $scope.showFiles = [];
    $scope.upFile=function(){
        var obj = $("#uploadFile")[0];
        var isHaveFile = false;
        $scope.showFiles.forEach(function(item){
            if(item.myFileRealName===obj.files[0].name){
                isHaveFile = true;
            }
        });
        if(isHaveFile){
            showMessage('warning','',"已存在同名文件或重复文件！");
            return false;
        }
        $scope.showFiles.push({
            myFileRealName:obj.files[0].name,
            myFileSize:obj.files[0].size,
            isSuccess:false,
            isCancel:false,
            isError:false,
            isUploading:false,
            progress:0,
            file:obj.files[0]
        });
    };
    $scope.doupFile=function(index){
        uploadFiles(index);
    };

    function makeFileData(data){
        data.forEach(function(item){
            item.progress = 100;
            item.isSuccess = true;
            item.isCancel = true;
            item.isError = false;
            item.isUploading = true;
        });
        $scope.showFiles = data;
    }
    function getAllFile(){
        toaster.getInfo('/a_yongan/file/getallfile/'+$scope.row.processProcessJgdh,null).then(function(data){
            if(data && data.data && data.data.success){
                makeFileData(data.data.data);
            }
        });
    }
    $scope.deleteFile = function (index) {
        if(!$scope.showFiles[index].isUploading){
            $scope.showFiles.splice(index,1);
        }else{
            toaster.getInfo('/a_yongan/file/deletefile/'+$scope.showFiles[index].myFileId,null).then(function(data){
                if(data && data.data && data.data.success){
                    $scope.showFiles.splice(index,1);
                    showMessage('success','','删除成功！');
                }else{
                    showMessage('warning','','删除失败！');
                }
            });
        }
    };
    function uploadFiles(index){
        $scope.showFiles[index].isUploading = true;
        var formData = new FormData();
        //formData.append("file",$("#uploadFile")[0].files[0]);//append()里面的第一个参数file对应permission/upload里面的参数file
        formData.append("file",$scope.showFiles[index].file);
        $.ajax({
            type:"post",
            async:true,  //这里要设置异步上传，才能成功调用myXhr.upload.addEventListener('progress',function(e){}),progress的回掉函数
            Accept:'text/html;charset=UTF-8',
            data:formData,
            //contentType:'multipart/form-data',
            url: '/a_yongan/file/upload/processingsheet/'+$scope.row.processProcessJgdh,
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            xhr:function(){
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ // check if upload property exists
                    myXhr.upload.addEventListener('progress',function(e){
                        var loaded = e.loaded;                  //已经上传大小情况
                        var total = e.total;                      //附件总大小
                        var percent = Math.floor(100*loaded/total);     //+"%"已经上传的百分比
                        $scope.showFiles[index].progress = percent;
                        //$("#processBar").css("width",percent);
                    }, false); // for handling the progress of the upload
                }
                return myXhr;
            },
            success:function(data){
                if(data.success){
                    showMessage('success','','上传成功！');
                    $scope.showFiles[index].myFileId = data.error;
                    $scope.showFiles[index].progress = 100;
                    $scope.showFiles[index].isUploading = true;
                    $scope.showFiles[index].isSuccess = true;
                }else{
                    showMessage('warning','',data.error);
                    $scope.showFiles[index].isUploading = false;
                    $scope.showFiles[index].isSuccess = false;
                }
            },
            error:function(){
                showMessage('warning','','上传失败！');
                $scope.showFiles[index].isUploading = false;
                $scope.showFiles[index].isError = true;
            }
        });
    }
    inIt();
    $scope.isPrint = false;
    $scope.myPrintShow = function(){
        $scope.isPrint = !$scope.isPrint;
        $scope.warehouseAdd = !$scope.warehouseAdd;
    };
    $scope.myPrint = function(){
        var input = $('#orderPrint');
        input.print({
            globalStyles:true,
            noPrintSelector:'.no-print'
        });
    };

    $scope.showFlowDetailsShow = false;
    $scope.showFlowDetailsData = [];
    $scope.showFlowDetails = function(){
        if($scope.showFlowDetailsShow){
            $scope.showFlowDetailsShow = false;
        }else{
            $scope.showFlowDetailsShow = true;
            toaster.getInfo('/a_yongan/list/processrecording/'+$scope.row.processProcessId,null).then(function(data){
                if(data && data.data && data.data.data){
                    data.data.data.forEach(function(item){
                        item.createTime = $filter("date")(item.createTime, "yyyy-MM-dd HH:mm:ss");
                        if(item.prType==="起草"){
                            item.prFlowToName = "提单";
                            item.prToUser = item.prUser;
                        }
                    })
                    $scope.showFlowDetailsData = data.data.data;
                }
            });
        }
    };

    $scope.actions = {
        showListDetails:function(thisDom){
            var id=thisDom.processProcessId;
            var idDom = $("."+id);
            if(idDom && idDom.css("display")==="none"){
                idDom.css("display","");
            }else{
                idDom.css("display","none");
            }
        },
        closeAll:function(){
            $scope.saveDate.forEach(function(item){
                $("."+item.processProcessId).css("display","none");
            });
        },
        openAll:function(){
            $scope.saveDate.forEach(function(item){
                $("."+item.processProcessId).css("display","");
            });
        },
        search:function(){
            var postData={searchZdrId:"",searchStart:"",searchEnd:"",searchHpmcId:"",
                searchBm:"",searchOrderBm:"",searchType:"",
                searchDingStart:"",searchDingEnd:"",searchSendStart:"",searchSendEnd:"",
                searchSlStart:"",searchSlEnd:"",searchJeStart:"",searchJeEnd:"",
                searchCzrId:"",searchJyrId:""};
            postData.searchZdrId = $("#searchZdrId").val();
            postData.searchStart = new Date($("#searchStart").val()).getTime();
            postData.searchEnd = new Date($("#searchEnd").val()).getTime();
            postData.searchHpmcId = $("#searchHpmcId").val();
            postData.searchBm = $("#searchBm").val();
            postData.searchOrderBm = $("#searchOrderBm").val();
            postData.searchType = $scope.lists[$("#searchType").val()];
            postData.searchJgType = $scope.listsJg[$("#searchJgType").val()];
            postData.searchDingStart = new Date($("#searchDingStart").val()).getTime();
            postData.searchDingEnd = new Date($("#searchDingEnd").val()).getTime();
            postData.searchSendStart = new Date($("#searchSendStart").val()).getTime();
            postData.searchSendEnd = new Date($("#searchSendEnd").val()).getTime();
            postData.searchSlStart = $("#searchSlStart").val()==""?"0":$("#searchSlStart").val();
            postData.searchSlEnd = $("#searchSlEnd").val()==""?"0":$("#searchSlEnd").val();
            postData.searchJeStart = $("#searchJeStart").val()==""?"0":$("#searchJeStart").val();
            postData.searchJeEnd = $("#searchJeEnd").val()==""?"0":$("#searchJeEnd").val();
            postData.searchCzrId = $("#searchCzrId").val();
            postData.searchJyrId = $("#searchJyrId").val();

            toaster.postInfo('/a_yongan/selectall/processingSheet',postData).then(function(data){
                if(data && data.data && data.data.data){
                    makeData(data.data.data);
                }
            });
        }
    };

    $scope.excel = function(){
        toaster.tableToExcel('tableToExcel', '下载模板');
    };
}])
;